<template>
    <view>
        <!-- 订单详情 -->
        <order-item v-for="(item, index) in list" :OriginData="item" :type="type" @change="onCountChange" :key="index" />
        <!-- 退款说明 -->
        <view class="refund-reason">
            <view class="refund-reason-title">退款说明</view>
            <view class="refund-reason-desc">
                <u-input v-model="description" placeholder="输入退款原因" border></u-input>
            </view>
            <view class="refund-reason-title">订单信息</view>
            <view class="refund-reason-info">
                <view>商品总金额：￥{{ Number(totalPrice).toFixed(2) }}</view>
                <view v-if="freight > 0">
                    <text>运费：￥{{ Number(freight).toFixed(2) }} </text>
                    <text class="tips">(全部退时才退运费)</text>
                </view>
                <view v-if="amountPrice > 0">优惠：￥{{ Number(amountPrice).toFixed(2) }}</view>
                <view>实付金额：￥{{ Number(totalPrice + freight - amountPrice).toFixed(2) }}</view>
                <view>本次退款金额：￥{{ Number(totalRefund + (needRefundFreight ? freight : 0)).toFixed(2) }}</view>
                <view>占总订单金额：{{ totalPrice > 0 ? Number((priceBeforeComputed / totalPrice) * 100).toFixed(2) : 0 }} %</view>
            </view>
        </view>
        <!-- 上传凭证 -->
        <view class="upload-evidence">
            <view class="title">上传凭证</view>
            <view class="action">
                <u-upload ref="uUpload" :action="global.CREDupload" :max-size="global.DEFAULT_IMAGE_SIZE" max-count="5" :header="header" name="file" :multiple="false" @on-success="onSuccess"></u-upload>
            </view>
            <view class="holder" style="height: 60px"> </view>
            <view class="btn">
                <view class="safe-area-inset-bottom">
                    <u-button type="p" class="btn-submit" @click="submit">确认提交</u-button>
                </view>
            </view>
        </view>
    </view>
</template>

<script lang="ts" setup>
import { nextTick, ref } from 'vue'
import orderItem from '../compoments/items.vue'
import global from '@/config'
import { useUserStore } from '@/store'
import { onLoad, onReady } from '@dcloudio/uni-app'

const list = ref([])

let id = ''

const type = ref(0)

const description = ref('')
/** 订单总金额 */
const totalPrice = ref(0)
/** 运费 */
const freight = ref(0)
/** 订单总退款 */
const totalRefund = ref(0)
/** 优惠金额 */
const amountPrice = ref(0)
/** 是否需要退运费 */
const needRefundFreight = ref(false)

const priceBeforeComputed = ref(0)

const sum = ref(0)

const userStore = useUserStore()

const header = {
    'MERCHANT-token': userStore.token
}

let fileList: Array<any> = []

function onCountChange() {
    nextTick(() => {
        let count = 0 // 件数
        let refund = 0 // 退款总金额
        let bakPrice = 0 // 价格计算前的数据
        // 数量改变之后 需要修改汇总的属性值
        list.value.forEach((item: any) => {
            let num = 0 // 退货商品件数
            let price = 0 // 退款金额
            item.sku.forEach((m: any) => {
                num += m.refundNum
                // 退款商品金额 占 总金额的占比 * 优惠金额 = 当前商品的 优惠金额
                price += m.refundNum * m.singlePrice
                bakPrice += m.refundNum * m.singlePrice // 接口需要未优惠前的价格
            })
            refund += price
            count += num
        })
        // 如果全退  则需要加上运费
        needRefundFreight.value = count == sum.value

        totalRefund.value = refund - Number(Number(refund / totalPrice.value).toFixed(2)) * amountPrice.value
        priceBeforeComputed.value = bakPrice
    })
}

function submit() {
    if (description.value == '') {
        uni.$u.toast('请输入退款原因!')
        return
    }
    let __list = []
    let refundGoodsNum = 0
    list.value.map((skus: any) => {
        skus.sku.map((sku: any) => {
            if (sku.refundNum != 0) {
                refundGoodsNum += sku.refundNum
                __list.push({
                    orderSubDetailId: sku.id,
                    refundAmount: sku.singlePrice * sku.refundNum,
                    refundGoodsNum: sku.refundNum
                })
            }
        })
    })
    if (__list.length === 0) {
        uni.$u.toast('请选择要退款的规格及数量!')
        return
    }
    let para = {
        orderId: id,
        merchantId: userStore.userInfo.merchantId,
        refundAmount: Number(priceBeforeComputed.value).toFixed(2),
        refundGoodsNum: refundGoodsNum,
        remark: description.value,
        proofFileIds: fileList,
        orderRefundSubDetailList: list,
        refundFreightType: needRefundFreight.value ? 1 : 0
    }
    uni.$u.$api.OrderApi.saveOrderRefund(para).then((res: any) => {
        uni.$u.$MRouter.refundDetail.to({ id: res }, 'redirectTo')
    })
}

function onSuccess(data: any, index: number, list: Array<any>) {
    if (data.code != 1) {
        uni.$u.toast('上传失败,请重试!')
        list[index].error = true
        list[index].file = undefined
        list[index].url = undefined
    } else {
        fileList = list.map((m: any) => {
            return m.response.data.id
        })
    }
}
onLoad((option: any) => {
    id = option.id
})

onReady(() => {
    uni.$u.$api.OrderApi.queryOrderDetail({
        id: id
    }).then((res: any) => {
        type.value = res.order.type
        // 初始化值
        list.value = res.skus
        // 计算订单总数量
        let temp = 0
        res.skus.map((m: any) => {
            m.sku.map((n: any) => {
                temp += n.num
            })
        })
        sum.value = temp
        totalPrice.value = res.order.totalPrice
        freight.value = res.order.freight
        amountPrice.value = res.order.amountPrice
    })
})
</script>

<style scoped lang="scss">
.refund {
    &-reason {
        margin-top: 20rpx;
        background-color: $uni-bg-color;
        padding: 30rpx 0;
        &-title {
            line-height: 100rpx;
            font-size: 30rpx;
            font-weight: 600;
            padding-left: 30rpx;
            &::after {
                content: '*';
                color: red;
            }
        }
        &-desc {
            padding: 0 30rpx;
        }
        &-info {
            padding: 0 30rpx;
            line-height: 80rpx;
            & > view {
                border: 1rpx solid #fff4f5;
                padding: 0 20rpx;
            }
            & > view:nth-child(2n + 0) {
                background-color: #fff4f5;
                color: #ff2442;
            }
        }
    }
    &-detail {
        background-color: $uni-bg-color;
    }
    &-item-footer {
        line-height: 60rpx;
        padding: 0 30rpx;
        border-top: 1rpx solid #f8f8f8;
    }
}
.upload-evidence {
    background-color: $uni-bg-color;
    .title {
        padding: 0 30rpx;
        font-size: 30rpx;
        font-weight: 600;
    }
    .btn-submit {
        width: 50%;
    }
    .action {
        padding: 30rpx;
    }
}
.btn {
    position: fixed;
    width: 100%;
    bottom: 0rpx;
    background-color: white;
    padding: 20rpx;
    z-index: 99;
}
.tips {
    margin-left: 20rpx;
    color: #8c8c8c;
    font-size: 24rpx;
}
</style>
